package com.aphrodite.io.sip.call;

import com.aphrodite.io.sip.address.NameAddress;
import com.aphrodite.io.sip.message.Message;
import com.aphrodite.io.sip.message.SipMethods;
import com.aphrodite.io.sip.provider.MethodIdentifier;
import com.aphrodite.io.sip.provider.SipProvider;
import com.aphrodite.io.sip.provider.SipProviderListener;

/**
 * CallAccepter listens for new incoming invite requests that create an Call.
 */
public class CallAccepter implements SipProviderListener {
	/** From URL (user's AOR). */
	// String from_url;
	/** Contact URL. */
	String contact_url;

	/** CallAccepterListener that captures new calls. */
	CallAccepterListener listener;

	/** SipProvider that receives incoming invite requests. */
	SipProvider sip_provider;

	/**
	 * Creates a new CallAccepter of type <i>method</i>, and starts listening
	 * for incoming invite requests.
	 */
	public CallAccepter(SipProvider sip_provider, /* String from_url, */String contact_url, CallAccepterListener listener) {
		this.listener = listener;
		this.sip_provider = sip_provider;
		// this.from_url=from_url;
		this.contact_url = contact_url;
		sip_provider.addSipProviderListener(new MethodIdentifier(SipMethods.INVITE), this);
	}

	/** Stops listening for incoming invite requests. */
	public void halt() {
		sip_provider.removeSipProviderListener(new MethodIdentifier(SipMethods.INVITE));
	}

	/** Method derived from interface SipListener. */
	public void onReceivedMessage(SipProvider provider, Message msg) {
		NameAddress callee = msg.getToHeader().getNameAddress();
		NameAddress caller = msg.getFromHeader().getNameAddress();
		String sdp = msg.getBody();
		if (listener != null)
			listener.onNewCall(this, new ExtendedCall(sip_provider, msg, contact_url, listener), callee, caller, sdp,
					msg);
	}

}
